#include <pyloader.h>
#include <dlfcn.h>
int PreeditTextChanged(char* buffer, uint32_t len, void* data)
{	
	PyObject* handler = ICGetCallale(data,"PreeditTextChanged");
	if(handler == NULL) return -1;
	PyObject* buf = Py_BuildValue("(s)",buffer);
	PyObject* res = PyObject_Call(handler, buf, NULL);
	int rc = 0;
	if(NULL == res) PyErr_Print(), rc = -1;
	else Py_DECREF(res);
	Py_DECREF(handler);
	Py_DECREF(buf);
	return rc;
}
int Enabled(void* ic)
{
	if(CreateIMObject(ic) == -1) return -1;
	PyObject* handler = ICGetCallale(ic,"Enabled");
	if(handler == NULL) return 0;
	PyObject* arg = Py_BuildValue("()");
	PyObject* ret = PyObject_Call(handler, arg, NULL);
	int rc = 0;
	if(NULL == ret) PyErr_Print(), rc = -1;
	else Py_DECREF(ret);
	Py_DECREF(handler);
	Py_DECREF(arg);
	return rc;
}
int Disabled(void* ic)
{

	PyObject* handler = ICGetCallale(ic,"Disabled");
	if(handler)
	{
		PyObject* arg = Py_BuildValue("()");
		PyObject* ret = PyObject_Call(handler, arg, NULL);
		if(NULL == ret) PyErr_Print();
		else Py_DECREF(ret);
		Py_DECREF(handler);
		Py_DECREF(arg);
	}
	DestoryIMObject(ic);
	return 0;
}
int Initialize(char* param,void* IC)
{
	/* dirty hack */
	if(dlopen("libpython2.7.so", RTLD_LAZY | RTLD_GLOBAL));
	else if(dlopen("libpython2.6.so", RTLD_LAZY | RTLD_GLOBAL));
	else if(dlopen("libpython2.5.so", RTLD_LAZY | RTLD_GLOBAL));
	static int flag = 0;
	if(!flag) 
	{
		flag = 1;
		InitPython(IC);
	}
	return 0;
}
int Finalize()
{
	Py_Finalize();
	return 0;
}
MetaDataBegin(VinePythonLoader, InputContext, 1)
	IMSetMetaData(NCandidates,32);
	IMRegisterEventHandler(OnInitialize,Initialize);
	IMRegisterEventHandler(OnFinalize,Finalize);
	IMRegisterEventHandler(OnEnabled, Enabled);
	IMRegisterEventHandler(OnDisabled,Disabled);
	IMRegisterEventHandler(OnPreeditTextChanged,PreeditTextChanged);
MetaDataEnd
